#include "imageview.h"
#include "mainwindow.h"

#include <windows.h>
#include <QtWidgets>

ImageView::ImageView(QWidget *parent)
    : QWidget{parent}
{}

void ImageView::setPixmap(const QImage &image)
{
    this->image = image;
    scaleFactor = this->width() * 1.0 / this->image.width();
    posCur = {0, 0};
    isflipvertical = false;
    update();
    updateViewInfo();
}

void ImageView::save()
{
    auto fileName = qApp->applicationDirPath() + "/1.png";
    image.mirrored(isflipvertical, false).copy(QRect(-1 * posCur, this->size() / scaleFactor)).save(fileName);


    //壁纸注册表表
    QSettings wallPaper("HKEY_CURRENT_USER\\Control Panel\\Desktop",
                        QSettings::NativeFormat);
    //新的桌面图片路径
    QString path = fileName;

    //给壁纸注册表设置新的值（新的图片路径）
    wallPaper.setValue("Wallpaper",path);
    QByteArray byte = path.toLocal8Bit();

    //调用windowsAPI
    SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, byte.data(), SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}

void ImageView::flipvertical()
{
    isflipvertical = !isflipvertical;
    update();
}

void ImageView::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.fillRect(this->rect(), Qt::red);
    painter.scale(scaleFactor, scaleFactor);
    painter.drawImage(posCur + posOff, image.mirrored(isflipvertical, false));

    qreal barHeight = SystemTaskBarHeight * 1.0 * this->height() / 1080;
    painter.fillRect(QRect(0, (this->height() - barHeight) / scaleFactor, this->width() / scaleFactor, barHeight / scaleFactor), QColor(200, 200, 200, 200));
}

void ImageView::wheelEvent(QWheelEvent *event)
{
    scaleFactor += event->delta() / 1200.0 / 10;
    update();
    updateViewInfo();
}

void ImageView::mousePressEvent(QMouseEvent *event)
{
    isPressed = true;
    posPressed = event->pos();
}

void ImageView::mouseMoveEvent(QMouseEvent *event)
{
    posOff = event->pos() - posPressed;
    posOff /= scaleFactor;
    update();
    updateViewInfo();
}

void ImageView::mouseReleaseEvent(QMouseEvent *event)
{
    posCur += posOff;
    posOff = {0, 0};
    isPressed = false;
}

void ImageView::updateViewInfo()
{
    if(MainWindow *w = qobject_cast<MainWindow *>(this->window())) {
        QRect r = QRect(-1 * (posCur + posOff), this->size() / scaleFactor);
        w->updateViewInfo(QString("rect(%1,%2 %3x%4), scale(%5)")
                              .arg(r.x())
                              .arg(r.y())
                              .arg(r.width())
                              .arg(r.height())
                              .arg(scaleFactor)
                          );
    }
}
